import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { STColumn } from '@delon/abc'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { ACLService } from '@delon/acl'

import { I18NService } from '@core'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { ISearchSchema, ISearchOption } from '@shared/interfaces/search'
import { ESearchType, ETradeChannel, EPaymentBrand } from '@shared/enums'
import { IAcquirerQueryParams, Acquirer, Common } from '@shared/interfaces/acquirer'
import { AcquirerService } from '../acquirer.service'
import { Country, Currency } from '@shared/interfaces/common'
import { IAamsItem } from '@shared/components/aams-select/aams-select.interface'
import { AAMSFilterInit } from '@shared/interfaces/aams'
import { SettingsService } from '@delon/theme'
import { ModalService } from '@shared/services/modal.service'
import { PublicService } from '@shared/services/public.service'
import { Observable } from 'rxjs'
import { ChannelService } from '@shared/services/channel.service'

@Component({
  selector: 'app-trades-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../shared/styles/table.less'],
})
export class AcquirerListComponent extends ListBaseClass<Acquirer, IAcquirerQueryParams>
  implements OnInit, AAMSFilterInit {
  selectedAcquirer: IAamsItem
  selectedCountry: Country
  selectedCurrency: Currency

  @ViewChild('tplAcquirer') tplAcquirer: TemplateRef<void>
  @ViewChild('tplCountry') tplCountry: TemplateRef<void>
  @ViewChild('tplCurrency') tplCurrency: TemplateRef<void>
  @ViewChild('tplChannel') tplChannel: TemplateRef<void>

  channelOptions$: Observable<ISearchOption[]>
  channelOptions: ISearchOption[] = []
  selectedChannel: EPaymentBrand

  searchSchema: ISearchSchema[] = []

  customSchema: ISearchSchema[] = []

  data: Acquirer[] = []
  columns: STColumn[] = []

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    public settings: SettingsService,
    public aclService: ACLService,
    private acquirerService: AcquirerService,
    private modalService: ModalService,
    private publicService: PublicService,
    private channelService: ChannelService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit() {
    this.initChannelOptions()
    this.initSearchParams()
    this.initColumns()
    this.parseParams().subscribe(() => {
      this.queryTableDataWithParams()
      this.initColumns()
    })
    this.initialAAMSFilter()
  }

  freezeDialog(record: Common): void {
    const { insName } = record
    const msg = this.trans('GENERAL.NOTIFICATION.INSTITUTION_FREEZE_CONFIRM', { insName })
    this.modalService.freezeAndUnFreeze(msg).subscribe(isOK => {
      if (!isOK) return
      this.freeze(record)
    })
  }

  unfreezeDialog(record: Common): void {
    const { insName } = record
    const msg = this.trans('GENERAL.NOTIFICATION.INSTITUTION_UNFREEZE_CONFIRM', { insName })
    this.modalService.freezeAndUnFreeze(msg).subscribe(isOK => {
      if (!isOK) return
      this.unfreeze(record)
    })
  }

  freeze(record: Common): void {
    const { insCode } = record
    this.acquirerService.freeze(insCode).subscribe(
      success => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_SUCCESS'))
        this.st.reload()
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.FREEZE_FAIL'))
      },
    )
  }

  unfreeze(record: Common): void {
    const { insCode } = record
    this.acquirerService.unfreeze(insCode).subscribe(
      success => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_SUCCESS'))
        this.st.reload()
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.UNFREEZE_FAIL'))
      },
    )
  }

  initialAAMSFilter() {
    this.initAcquirer()
  }

  initSearchParams(): void {
    this.searchSchema = [
      {
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        index: 'createAt',
        type: ESearchType.dateRange,
        value: [],
      },
      {
        label: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        labelI18n: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        index: 'insCode',
        component: this.tplAcquirer,
        customFunc: () => this.selectedAcquirer && this.selectedAcquirer.code,
      },
      {
        label: 'GENERAL.INFO.COUNTRY_REGION',
        labelI18n: 'GENERAL.INFO.COUNTRY_REGION',
        index: 'nation',
        component: this.tplCountry,
        customFunc: () => this.selectedCountry && this.selectedCountry.codeAlpha3,
      },
      {
        label: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        labelI18n: 'GENERAL.INFO.TRANSACTION_CURRENCY',
        index: 'currency',
        component: this.tplCurrency,
        customFunc: () => this.selectedCurrency && this.selectedCurrency.code,
      },
      {
        label: 'GENERAL.INFO.CHANNEL',
        labelI18n: 'GENERAL.INFO.CHANNEL',
        index: 'channel',
        component: this.tplChannel,
        customFunc: () => this.selectedChannel,
      },
      {
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        type: ESearchType.selection,
        options: [
          { label: this.trans('GENERAL.STATUS.NORMAL'), value: 'normal' },
          { label: this.trans('GENERAL.STATUS.FREEZE'), value: 'freeze' },
        ],
      },
    ]
  }

  initColumns(): void {
    const canLock = this.aclService.canAbility('api.put.camel.institution.one.freeze')
    const canUnlock = this.aclService.canAbility('api.put.camel.institution.one.unfreeze')
    this.columns = [
      {
        type: 'link',
        title: '机构号',
        i18n: this.trans('GENERAL.INSTITUTION.CODE'),
        index: 'insCode',
        className: 'text-center p-xs',
        width: '150px',
        fixed: 'left',
        click: this.goDetail.bind(this),
      },
      {
        title: '机构名称',
        i18n: this.trans('GENERAL.INSTITUTION.NAME'),
        index: 'insName',
        width: '200px',
        className: 'text-left',
      },
      {
        title: '机构英文名称',
        i18n: this.trans('GENERAL.INSTITUTION.NAME_EN'),
        index: 'insNameEN',
        width: '200px',
        className: 'text-left',
      },
      {
        title: '国家/地区',
        i18n: this.trans('GENERAL.INFO.COUNTRY_REGION'),
        index: 'address.nation',
        width: '100px',
        className: 'text-center',
      },
      {
        title: '创建时间',
        i18n: this.trans('GENERAL.INFO.CREATED_AT'),
        index: 'createdAt',
        className: 'text-center',
        width: '150px',
        type: 'date',
        dateFormat: 'YYYY-MM-DD HH:mm',
      },
      {
        title: '操作',
        i18n: this.trans('GENERAL.INFO.OPERATION'),
        width: '150px',
        fixed: 'right',
        className: 'text-center p-xs',
        iif: () => canLock || canUnlock,
        buttons: [
          {
            text: '',
            icon: {
              iconfont: 'icon-lock-twotone',
              type: 'iconfont',
            },
            click: this.freezeDialog.bind(this),
            iif: record => canLock && record.status === 'normal',
          },
          {
            text: '',
            icon: {
              iconfont: 'icon-unlock-circle',
              type: 'iconfont',
            },
            click: this.unfreezeDialog.bind(this),
            iif: record => canUnlock && record.status === 'freeze',
          },
        ],
      },
    ]
  }

  goAdd(): void {
    this.router.navigate(['../new'], { relativeTo: this.route })
  }

  goDetail(record: Common): void {
    const { insCode } = record
    this.router.navigate([`../${insCode}`], { relativeTo: this.route })
  }

  /* 覆盖父类方法 */
  renderList(res): void {
    const { data, total } = res
    this.data = data ? data.map(d => {
      return { ...d.common, createdAt: d.createdAt }
    }) : []
    this.total = total
    this.loading = false
  }

  queryTableDataWithParams(): void {
    this.loading = true
    this.acquirerService.getList(this.params).subscribe(this.renderList.bind(this), this.getListError.bind(this))
  }

  private initChannelOptions(): void {
    this.channelOptions$ = this.channelService.getCurrentSupportChannelOptions()
  }
}
